<template>
  <div class="stock-in-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>入库管理</span>
          <div class="right-buttons">
            <el-button type="success" @click="exportStockIn">导出Excel</el-button>
            <el-button type="primary" @click="createStockIn">新建入库单</el-button>
          </div>
        </div>
      </template>

      <el-form :model="queryParams" label-width="100px" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="入库单号">
              <el-input v-model="queryParams.stock_in_no" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-input v-model="queryParams.supplier" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100%">
                <el-option label="全部" :value="null" />
                <el-option label="待审核" :value="0" />
                <el-option label="已审核" :value="1" />
                <el-option label="已取消" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="stockIns" border style="width: 100%">
        <el-table-column prop="stock_in_no" label="入库单号" />
        <el-table-column label="供应商">
          <template #default="{ row }">
            {{ row.supplier.name }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="总金额">
          <template #default="{ row }">
            ￥{{ formatPrice(row.total_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="statusTagType[row.status]">
              {{ statusMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人">
          <template #default="{ row }">
            {{ row.create_user.name }}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">详情</el-button>
            <el-button size="small" type="danger" v-if="row.status === 0" @click="deleteStockIn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :total="total"
        @current-change="getList"
        layout="prev, pager, next"
        style="margin-top: 20px;"
      />
    </el-card>

    <!-- 创建入库单 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="50%">
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-form-item label="供应商">
          <el-select v-model="formData.supplier" placeholder="请选择供应商" style="width: 100%">
            <el-option
              v-for="item in suppliers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <h4>商品明细</h4>
        <el-table :data="formData.details" border style="margin-bottom: 20px;">
          <el-table-column prop="product" label="商品">
            <template #default="{ row }">
              <el-select v-model="row.product" placeholder="请选择商品" style="width: 100%">
                <el-option
                  v-for="item in products"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价">
            <template #default="{ row }">
              <el-input-number v-model="row.price" :precision="2" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :precision="0" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button @click="removeDetail($index)" type="danger" circle>-</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addDetail">添加商品</el-button>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="drawerVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 入库单详情 -->
    <el-drawer v-model="detailDrawerVisible" title="入库单详情" size="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="入库单号">{{ detailData.stock_in_no }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ detailData.supplier?.name }}</el-descriptions-item>
        <el-descriptions-item label="总金额">￥{{ formatPrice(detailData.total_amount) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTagType[detailData.status]">
            {{ statusMap[detailData.status] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.create_user?.name }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.create_time }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.update_time }}</el-descriptions-item>
      </el-descriptions>

      <h4 style="margin-top: 20px;">商品明细</h4>
      <el-table :data="detailData.details" border>
        <el-table-column prop="product.name" label="商品名称" />
        <el-table-column prop="price" label="单价">
          <template #default="{ row }">
            ￥{{ formatPrice(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" />
        <el-table-column label="金额">
          <template #default="{ row }">
            ￥{{ formatPrice(row.amount) }}
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const stockIns = ref([])
const total = ref(0)
const queryParams = ref({
  page: 1,
  size: 10,
  stock_in_no: '',
  supplier: '',
  status: null,
  beginTime: '',
  endTime: ''
})

const dateRange = ref([])

const statusMap = {
  0: '待审核',
  1: '已审核',
  2: '已取消'
}

const statusTagType = {
  0: 'warning',
  1: 'success',
  2: 'danger'
}

const drawerVisible = ref(false)
const drawerTitle = ref('')
const detailDrawerVisible = ref(false)
const detailData = ref({})
const suppliers = ref([])
const products = ref([])

const formData = ref({
  supplier: null,
  details: [
    { product: null, price: 0, quantity: 1 }
  ]
})

const exportStockIn = () => {
  const params = {
    stock_in_no: queryParams.value.stock_in_no,
    beginTime: queryParams.value.beginTime,
    endTime: queryParams.value.endTime,
    status: queryParams.value.status
  }
  request({
    url: '/stock-in/export/',
    method: 'GET',
    params,
    responseType: 'blob', // 设置响应类型为 blob
    isFileDownload: true
  }).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'stock_in.xlsx') // 设置下载文件名
    document.body.appendChild(link)
    link.click()
  })
}

const getSuppliers = async () => {
  const res = await request.get('/supplier/')
  suppliers.value = res.records
}

const getProducts = async () => {
  const res = await request.get('/product/')
  products.value = res.records
}

const getList = async () => {
  try {
    const params = { ...queryParams.value }
    if (dateRange.value && dateRange.value.length >= 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }

    const res = await request.get('/stock-in/', { params })
    stockIns.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取入库单失败:', error)
  }
}

const createStockIn = () => {
  drawerTitle.value = '新建入库单'
  drawerVisible.value = true
  formData.value = {
    supplier: null,
    details: [
      { product: null, price: 0, quantity: 1 }
    ]
  }
}

const viewDetail = (row) => {
  detailData.value = { ...row }
  detailDrawerVisible.value = true
}

const deleteStockIn = async (id) => {
  try {
    await request.delete(`/stock-in/${id}/`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const addDetail = () => {
  formData.value.details.push({ product: null, price: 0, quantity: 1 })
}

const removeDetail = (index) => {
  formData.value.details.splice(index, 1)
}

const submitForm = async () => {
  try {
    await request.post('/stock-in/', formData.value)
    ElMessage.success('创建成功')
    drawerVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

const formatPrice = (price) => {
  return parseFloat(price).toFixed(2)
}

const search = () => {
  queryParams.value.page = 1
  getList()
}

const reset = () => {
  queryParams.value = {
    page: 1,
    size: 10,
    stock_in_no: '',
    supplier: '',
    status: null,
    beginTime: '',
    endTime: ''
  }
  dateRange.value = []
  getList()
}

onMounted(async () => {
  await Promise.all([getSuppliers(), getProducts()])
  getList()
})
</script>

<style scoped>
.stock-in-list {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
